package com.lwc.backendsinglestructure.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 滑动窗口限流拦截器
 */
@Component
public class RateLimitInterceptor implements HandlerInterceptor {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String apiKey = request.getHeader("X-API-KEY");
        String apiKey = "1";
        String key = "rate:limit:" + apiKey;
        // 限流的lua脚本
        Boolean b = allowRequest(key);
        // 拒绝请求
        if (!b){
            return false;
        }

        return true;
    }


    /**
     * 使用redis的zset数据结构实现滑动窗口限流
     * 可以限流对接口限流
     * 也可以对具体某个用户进行限流
     * @param key
     * @return
     */
    public Boolean allowRequest(String key){
        long current_time = System.currentTimeMillis();
        String lua = """
            local current_time = tonumber(ARGV[1])
            local window_start = current_time - 60000
            local max_requests = tonumber(ARGV[2])
            redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', window_start)
            local current_requests = redis.call('ZCARD', KEYS[1])
            if current_requests < max_requests then
                redis.call('ZADD', KEYS[1], current_time, current_time)
                return 1
            else
                return -1
            end
            """;

        Long result = redissonClient.getScript().eval(
                RScript.Mode.READ_WRITE,
                lua,
                RScript.ReturnType.INTEGER,
                Arrays.asList("limit:key:user1"),
                String.valueOf(current_time),
                "60"  // 最大请求数
        );

        return result == 1;
    }
}

